package io.mft.dev.base.config;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.yaml.snakeyaml.Yaml;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import io.mft.api.domain.Api;
import io.mft.dev.base.config.builder.CatalogApiBuilder.CatalogApi;
import lombok.extern.slf4j.Slf4j;

/**
 * 本地接口生成接口目录配置文件
 * @说明：TODO
 * @类型名称：ApiCatalogConfigGenerator
 * @创建者: 胡常建  
 * @创建时间: 2021年8月18日 下午4:56:19
 * @修改者: 胡常建  
 * @修改时间: 2021年8月18日 下午4:56:19
 */
@Slf4j
public class ApiCatalogConfigGenerator {

	public static void generateLocalApiCatalog(boolean devMode) {
		ApiCatalogYamlEditor apiCatalogYamlEditor=loadApiCatalogYamlEditor();
		apiCatalogYamlEditor.toYamlString(devMode);
	}
	public static ApiCatalogYamlEditor loadApiCatalogYamlEditor() {
		ApiCatalogYamlEditor apiCatalogYamlEditor=new ApiCatalogYamlEditor();
		try {
			String locationPattern = "classpath*:/config/api/**/*.json";
			PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new PathMatchingResourcePatternResolver());
			Resource[] resources = resolver.getResources(locationPattern);
			for (Resource resource : resources) {
				try {
					InputStream inputStream=resource.getURL().openStream();
					Charset charset = Charset.forName("UTF-8");
					String json=IoUtil.read(inputStream, charset);
					JSONObject jsonObject=new JSONObject(json);
					Api api=jsonObject.toBean(Api.class);
					String filename=resource.getFilename();
					String apiKey=filename.substring(0, filename.indexOf(".json"));
					CatalogApi catalogApi=new CatalogApi();
					catalogApi.setKey(apiKey);
					catalogApi.setSystemKey(api.getModule().getSystem().getKey());
					catalogApi.setModuleKey(api.getModule().getAliasKey());
					catalogApi.setApiFunctionType(api.getApiFunctionType());
					catalogApi.setDesc(api.getName());
					apiCatalogYamlEditor.addCatalogApi(catalogApi);
					log.warn("加载API配置目录,API路径["+resource.getURI().toURL().getPath()+"]");
				} catch (Exception e) {
					log.error("",e);
				}				
			}
		} catch (Exception e2) {
			// TODO: handle exception
		}
		return apiCatalogYamlEditor;
	}
	public static Map<String, Object> loadLocalApiCatalog() {
		Yaml yaml = new Yaml();
		ApiCatalogYamlEditor apiCatalogYamlEditor=loadApiCatalogYamlEditor();
		String text=apiCatalogYamlEditor.toYamlString(false);
		Map<String, Object> configObjectMap=yaml.load(text);
		return configObjectMap;
	}
}
